import React, {Component} from 'react';
import {Flex, List, InputItem, WingBlank, Modal, Button, Toast, Provider, DatePicker} from '@ant-design/react-native';
import {View, Text, Alert, Image} from 'react-native';
import {connect} from 'react-redux';
import SyanImagePicker from 'react-native-syan-image-picker';
import {uploadUserLogoFile} from '~/api/upload';
import {getImageFile} from '~/utils/request';
import {saveUserInfo} from '~/api/user';
import {saveUserInfo as updateUserInfo} from '~/store/userinfo';
import moment from 'moment';
import {TextInput} from 'react-native-gesture-handler';
import Spinner from 'react-native-loading-spinner-overlay';

const mapGetter = (state) => {
    return {
        userinfo: state.userinfo,
    };
};

const mapSetter = (dispatch) => {
    return {
        onSave: (data) => {
            dispatch(updateUserInfo(data));
        },
    };
};
class MyModify extends Component {
    static navigationOptions = {
        title: '修改信息',
    };
    constructor(props) {
        super(props);
        this.state = {
            tu: '',
            visible: false,
            files: [],
            name: this.props.userinfo.nickname,
            birthday: this.props.userinfo.birthday,
            urls: this.props.userinfo.logo,
            values: undefined,
            url: '',
            urlss: global.AppData.base_url,
            id: this.props.userinfo.mobile,
            spinner: false,
        };
        this.onChange = (value) => {
            this.setState({birthday: value});
        };
    }
    //图片上传
    onUpload = () => {
        this.setState({
            spinner: true,
        });
        uploadUserLogoFile(this.state.files).then((r) => {
            if (r.code === 0) {
                this.setState({
                    urls: r.data.url,
                    spinner: false,
                });
            } else {
                this.setState({
                    spinner: false,
                });
                Toast.info('上传失败，原因：' + r.msg, 1);
            }
        });
    };
    setFiles = () => {
        let files = [];
        files.push(getImageFile(this.state.tu, 'image'));
        this.setState(
            {
                files,
            },
            () => {
                this.onUpload();
            },
        );
    };
    onPress = () => {
        this.setState({
            visible: true,
        });
    };
    onClose = () => {
        this.setState({
            visible: false,
        });
    };

    //打开选择器: 选择多张图片
    _openPicker = () => {
        const options = {
            imageCount: 1, // 最大选择图片数目，默认6
            isCamera: true, // 是否允许用户在内部拍照，默认true
            isCrop: false, // 是否允许裁剪，默认false
            isRecordSelected: true,
            isGif: false, // 是否允许选择GIF，默认false，暂无回调GIF数据
            showCropCircle: false, // 是否显示圆形裁剪区域，默认false
            showCropFrame: true, // 是否显示裁剪区域，默认true
            showCropGrid: false, // 是否隐藏裁剪区域网格，默认false
            quality: 90,//压缩质量
        };
        SyanImagePicker.showImagePicker(options, (err, selectedPhotos) => {
            if (err) {
                // 取消选择
                return;
            }
            //选择成功，渲染图片
            this.setState(
                {
                    tu: selectedPhotos[0],
                },
                () => {
                    SyanImagePicker.removeAllPhoto();
                    this.setFiles();
                },
            );
        });
    };
    _openCamera = () => {
        const options = {
            imageCount: 1, // 最大选择图片数目，默认6
            isCamera: true, // 是否允许用户在内部拍照，默认true
            isCrop: false, // 是否允许裁剪，默认false
            isRecordSelected: true,
            isGif: false, // 是否允许选择GIF，默认false，暂无回调GIF数据
            showCropCircle: false, // 是否显示圆形裁剪区域，默认false
            showCropFrame: true, // 是否显示裁剪区域，默认true
            showCropGrid: false, // 是否隐藏裁剪区域网格，默认false
            quality: 90,//压缩质量
        };
        SyanImagePicker.openCamera(options, (err, photos) => {
            if (err) {
                // 取消选择
                return;
            }
            // 选择成功，渲染图片
            this.setState(
                {
                    tu: photos[0],
                },
                () => {
                    SyanImagePicker.removeAllPhoto();
                    this.setFiles();
                },
            );
            // ...
        });
    };
    submit = () => {
        if (this.state.name === '') {
            Toast.info('昵称内容不能为空', 1);
        } else if (this.state.birthday === '') {
            Toast.info('生日内容不能为空', 1);
        } else {
            saveUserInfo({
                nickname: this.state.name,
                birthday: this.state.birthday,
                logo: this.state.urls,
            }).then((r) => {
                if (r.code === 0) {
                    this.props.onSave({
                        nickname: this.state.name,
                        birthday: this.state.birthday,
                        logo: this.state.urls,
                    });
                    this.props.navigation.goBack();
                } else {
                    Toast.info('失败', 1);
                }
            });
        }
    };
    render() {
        const setName = (text) => {
            this.setState({
                name: text,
            });
        };
        return (
            <>
                <Flex direction={'column'} style={{backgroundColor: '#F6F6F6'}}>
                    {/* <WingBlank size={'lg'}> */}
                    <Spinner visible={this.state.spinner} textContent={'上传中...'} textStyle={{color: '#FFFFFF'}} />
                    <View
                        style={{
                            width: '100%',
                            height: 100,
                            flexDirection: 'row',
                            justifyContent: 'flex-start',
                            alignItems: 'center',
                            marginTop: 10,
                            paddingLeft: '5%',
                            backgroundColor: '#FFFFFF',
                        }}>
                        <Text style={{fontSize: 18}}>头像:</Text>
                        <Flex style={{width: '80%'}} justify="end" onPress={() => this.setState({visible: true})}>
                            {this.state.urls === '' ? (
                                <Image style={{width: 70, height: 70, borderRadius: 40}} source={require('~/assets/my/nantou.png')} />
                            ) : (
                                <Image style={{height: 70, width: 70, borderRadius: 40}} source={{uri: this.state.urlss + this.state.urls}} />
                            )}
                        </Flex>
                    </View>
                    {/* <View style={{ width: '100%', height: 2, backgroundColor: '#F6F6F6', marginTop: 10 }}></View> */}
                    <View style={{width: '100%', flexDirection: 'row', marginTop: 3, paddingHorizontal: '5%', backgroundColor: '#FFFFFF'}}>
                        <Flex justify="between" style={{width: '100%', height: 40}}>
                            <Text style={{fontSize: 18}}>昵称:</Text>
                            <TextInput
                                style={{width: '75%', direction: 'rtl', textAlign: 'right', marginRight: '8%'}}
                                placeholder="请输入"
                                onChangeText={setName}
                                value={this.state.name}
                            />
                        </Flex>
                    </View>
                    <View style={{width: '100%', height: 50, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center'}}>
                        <View style={{width: '100%'}}>
                            <List>
                                <DatePicker
                                    value={new Date(this.state.birthday)}
                                    mode="date"
                                    defaultDate={new Date()}
                                    minDate={new Date(1900, 1, 1)}
                                    maxDate={new Date()}
                                    onChange={this.onChange}
                                    format="YYYY-MM-DD">
                                    <List.Item arrow="horizontal">请选择生日:</List.Item>
                                </DatePicker>
                            </List>
                        </View>
                    </View>
                    <View
                        style={{
                            width: '100%',
                            height: 40,
                            flexDirection: 'row',
                            justifyContent: 'flex-start',
                            alignItems: 'center',
                            marginTop: 0,
                            paddingLeft: '5%',
                            backgroundColor: '#FFFFFF',
                        }}>
                        <Text style={{fontSize: 18}}>用户ID:</Text>
                        <Flex style={{width: '75%'}} justify="end">
                            <Text>{this.state.id}</Text>
                        </Flex>
                    </View>
                    <Modal popup visible={this.state.visible} animationType="slide-up" onClose={this.onClose}>
                        <Flex direction={'column'} justify={'center'} align={'center'}>
                            <Button
                                style={{width: 200, marginTop: 20}}
                                type={'primary'}
                                onPress={() => {
                                    this.onClose();
                                    this._openPicker();
                                }}>
                                相册
                            </Button>
                            <Button
                                style={{width: 200, marginTop: 20}}
                                type={'primary'}
                                onPress={() => {
                                    this.onClose();
                                    this._openCamera();
                                }}>
                                拍照
                            </Button>
                            <Button style={{width: '100%', marginTop: 30}} type={'warning'} onPress={this.onClose}>
                                取消
                            </Button>
                        </Flex>
                    </Modal>
                    <Button
                        style={{width: '80%', marginTop: '70%'}}
                        type={'warning'}
                        onPress={() => {
                            this.submit();
                        }}>
                        完成
                    </Button>
                    {/* </WingBlank> */}
                </Flex>
            </>
        );
    }
}
export default connect(mapGetter, mapSetter)(MyModify);
